package com.it.service.impl;

import com.it.context.BaseContext;
import com.it.exception.BaseException;
import com.it.mapper.UserMapper;
import com.it.pojo.dto.LoginDTO;
import com.it.pojo.dto.RegisterDTO;
import com.it.pojo.entity.User;
import com.it.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     * @param loginDTO 登录参数
     * @return 登录结果
     */
    @Override
    public User login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();

        // 1. 根据用户名查询用户
        User user = userMapper.getByUsername(username);

        // 2. 判断用户是否存在
        if (user == null) {
            throw new BaseException("用户不存在");
        }

        // 3. 判断密码是否正确
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            throw new BaseException("密码错误");
        }
        if (user.getStatus() == 0) {
            throw new BaseException("用户被禁用");
        }

        BaseContext.setCurrentId(user.getId());
        return user;
    }

    /**
     * 注册
     * @param registerDTO 注册参数
     */
    @Override
    @Transactional
    public void add(RegisterDTO registerDTO) {
        String username = registerDTO.getUsername();
        // 1. 判断用户名是否已存在
        User user = userMapper.getByUsername(username);
        if (user != null) {
            throw new BaseException("用户名已存在");
        }
        // 2. 校验两次密码是否一致
        if (!registerDTO.getPassword().equals(registerDTO.getRePassword())) {
            throw new BaseException("两次密码不一致");
        }
        // 3. 密码加密和添加用户
        registerDTO.setPassword(DigestUtils.md5DigestAsHex(registerDTO.getPassword().getBytes()));
        userMapper.add(registerDTO);
    }

    /**
     * 获取用户信息
     * @return 用户信息
     */
    @Override
    public User getUserInfo() {
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        return user;
    }
}
